package org.leon.demo.interceptor;

import org.leon.mvcframework.BaseInterceptor;
import org.leon.mvcframework.annotations.MvcInterceptor;
import org.leon.mvcframework.annotations.Security;
import org.leon.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by leon.L on 2020/2/1.
 * Desc : 全局的拦截器，拦截所有请求
 */
@MvcInterceptor
public class AuthInterceptor implements BaseInterceptor {

    @Override
    public boolean beforeHandler(HttpServletRequest request, HttpServletResponse response, Handler handler) {
        String uri = request.getRequestURI();

        String name = request.getParameter("name");
        if (name == null) {
            try {
                response.getWriter().write("Access deny!");
            }catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        // 判断 controller 上是否有 Security 注解，并判断当前请求的 name 是否允许访问
        Object controller = handler.getController();
        if (controller.getClass().isAnnotationPresent(Security.class)) {
            Security security = controller.getClass().getAnnotation(Security.class);
            String[] value = security.value();
            for (String s : value) {
                if (s.equals(name)) {
                    return true;
                }
            }
        }

        // 判断方法上是否有 Security 注解，并判断当前请求的 name 是否允许访问
        Method method = handler.getMethod();
        if (method.isAnnotationPresent(Security.class)) {
            Security security = method.getAnnotation(Security.class);
            String[] value = security.value();
            for (String s : value) {
                if (s.equals(name)) {
                    return true;
                }
            }
        }

        try {
            response.getWriter().write("Access deny!");
        }catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
